package cn.regexp.job.executor.jobHandler;

import cn.regexp.domain.ShopGoods;
import cn.regexp.service.IGoodsService;
import cn.regexp.utils.RedisKeys;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Component
public class GoodsXxlJob {
    private static Logger logger = LoggerFactory.getLogger(CanteenXxlJob.class);
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private IGoodsService goodsService;

    @XxlJob("cacheHotGoodsJobHandler")
    public void cacheHotGoodsJobHandler() throws Exception {
        XxlJobHelper.log("更新热门商品 --> start");
        String key = RedisKeys.HOT_GOODS_INFO.join();
        // 如果存在该 key，则删除
        if (Objects.equals(redisTemplate.hasKey(key),Boolean.TRUE)) {
            redisTemplate.delete(key);
        }
        // 将热门菜肴改为正常
        UpdateWrapper<ShopGoods> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("is_hot", ShopGoods.IS_NORMAL).eq("is_hot", ShopGoods.IS_HOT);
        goodsService.update(updateWrapper);
        // 查询符合要求的热门商品
        QueryWrapper<ShopGoods> wrapper = new QueryWrapper<>();
        wrapper.eq("state", ShopGoods.GOODS_UP).eq("sale_state", ShopGoods.GOODS_ON_SALE)
                .eq("is_del", ShopGoods.DELETE_NO);
        List<ShopGoods> shopGoods = goodsService.list(wrapper);
        logger.info("总共查询到" + shopGoods.size() + "个菜肴");
        // 统计数量
        shopGoods.forEach(item -> item.setCount(item.getViewNum() + item.getSaleNum() + item.getCollectNum()));
        // 根据统计数进行降序排序
        shopGoods.sort(Comparator.comparingInt(ShopGoods::getCount));
        // 获取排行前20的菜肴
        shopGoods = shopGoods.subList(0, Math.min(shopGoods.size(), 20));
        shopGoods.forEach(item -> {
            // 清除更新条件
            updateWrapper.clear();
            // 更新热卖状态
            updateWrapper.set("is_hot", ShopGoods.IS_HOT).eq("id", item.getId()).eq("is_del", ShopGoods.DELETE_NO);
            goodsService.update(updateWrapper);
        });
        // 将热门菜品信息存入 Redis 中，并设置 key 过期时间为1天
        redisTemplate.opsForValue().set(key, JSON.toJSONString(shopGoods),
                RedisKeys.HOT_GOODS_INFO.getTime(), TimeUnit.DAYS);
        XxlJobHelper.log("更新热门商品 --> end");
    }
}
